<template>
  <div class="container">
    <el-card>
      <div class="set-container">
        <div  class="select-container">
          <el-form ref="selectForm" :inline="true" :model="selectForm" class="select-form">
            <el-form-item prop="name" label="分类名称:">
              <el-input v-model="selectForm.name" placeholder="请输入名称" class="select-input-1" size="medium"></el-input>
            </el-form-item>
            <el-form-item prop="date" label="创建时间:">
              <el-date-picker
                  size="medium"
                  v-model="selectForm.date"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="status" label="分类状态">
              <el-select class="select-input-2" v-model="selectForm.status" placeholder="请选择" size="medium">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" size="medium" @click="submitSelect(1)">查询</el-button>
                <el-button type="info" size="medium" @click="resetSelect">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="button-container">
          <el-button type="success" size="medium" @click="addUser">新增分类</el-button>
          <el-button type="danger" size="medium" @click="showDialog">批量操作</el-button>
          <el-button type="info" size="medium">导出表格</el-button>
        </div>
      </div>
      <el-divider><h3 style="text-align: center">分类信息表格</h3></el-divider>
      <div class="table-container">
        <el-table
            v-if="tableData.length > 0"
            :data="tableData"
            @selection-change="handleSelectionChange"
            border
            stripe
            style="width: 100%"
        >
          <el-table-column
              type="selection"
              width="45">
          </el-table-column>
          <el-table-column
              prop="name"
              label="分类名"
              width="210">
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间"
              width="250">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="createUser"
              label="创建人"
              width="150">
          </el-table-column>
          <el-table-column
              prop="updateTime"
              label="更新时间"
              width="250">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              {{ formatCreateTime(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="updateUser"
              label="更新人"
              width="150">
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" effect="dark">启用</el-tag>
              <el-tag v-else-if="scope.row.status === 0" type="warning" effect="dark">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button-group>
                <el-button type="primary" icon="el-icon-edit" size="mini" plain @click="openEditUserDialog(scope.row.id)" >编辑</el-button>
                <el-button  v-if="scope.row.status===1" type="warning" icon="el-icon-lock" size="mini" plain @click="logout(scope.row.id,0)" >停用</el-button>
                <el-button  v-else icon="el-icon-unlock" size="mini" plain @click="logout(scope.row.id,1)">启用</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <el-empty :image-size=350  v-else description="暂无数据"></el-empty>
      </div>
      <el-divider></el-divider>
      <div class="page">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="selectForm.page"
            :page-sizes="[5, 7, 10, 20, 50]"
            :page-size="selectForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
import axios from "@/api/axios";

export default {
  data() {
    return {
      selectForm:{
        name:"",
        date:"",
        pageSize:7,
        page:1,
        status:"",
      },
      total:0,
      tableData:[],

      options: [
        {
          value: 0,
          label: '停用'
        }, {
          value: 1,
          label: '启用'
        }
      ],
    }
  },

  mounted() {
    this.submitSelect();
  },

  methods:{
    /**
     * 表格数据查询函数
     */
    submitSelect(flag) {
      this.$refs.selectForm.validate((valid) => {
        if (flag===1) {
          this.selectForm.page = 1;// 重新查询时，将页码置为第一页
        }
        if (valid) {
          const formData = {
            page: this.selectForm.page,
            pageSize: this.selectForm.pageSize,
            name: this.selectForm.name,
            begin: this.formatDate(this.selectForm.date[0]),
            end: this.formatDate(this.selectForm.date[1]),
            status: this.selectForm.status,
          };

          axios.post("/admin/category/list", formData).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 日期处理函数
     * @param date
     * @returns {null|string}
     */
    formatDate(date) {
      if (date instanceof Date) {
        // 返回格式化后的日期时间字符串（ISO 8601 UTC格式，不包含毫秒）
        return (
            date.toISOString().split("T")[0] +
            "T" +
            date.toISOString().split("T")[1].split(".")[0]
        );
      } else {
        // 如果日期为空或者不是Date对象，返回null或空字符串，或者根据你的需求返回其他默认值
        return null; // 或者 ""，取决于后端如何处理这种情况
      }
    },

    /**
     * 给返回的时间格式化函数
     * @param {Array} createTime - 包含年、月、日、时、分、秒的数组
     * @returns {string}
     */
    formatCreateTime(createTime) {
      const [year, month, day, hour, minute = '00', second = '00'] = createTime;
      return `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}:${this.padZero(second)}`;
    },

    /**
     * 将数字补零
     * @param {number|string} num
     * @returns {string}
     */
    padZero(num) {
      return num.toString().padStart(2, '0');
    },

    /**
     * 两个分页选项函数
     * @param val
     */
    handleSizeChange(val) {
      this.selectForm.pageSize = val;
      this.submitSelect();
    },
    handleCurrentChange(val) {
      this.selectForm.page=val;
      this.submitSelect();
    },

    /**
     * 查询表单重置函数
     */
    resetSelect() {
      this.$refs.selectForm.resetFields(this.selectForm);
      this.$message.info("重置成功");
    },
  }
}
</script>
<style scoped>
/*收缩选择框所占空间*/
.select-input-1{
  width: 100px;
}

.select-input-2{
  width: 120px;
}

/*表格最小高度*/
.table-container{
  min-height: 60vh;
}

/*表格顶部设置栏*/
.set-container{
  display: flex;
}

.button-container{
  margin-left: auto; /* 将按钮容器向右对齐 */
}

/*分页*/
.page{
  margin-top: 20px;
}
</style>
